package com.wdc.service.impl;

import com.wdc.common.constants.Constants;
import com.wdc.dao.IOrderDao;
import com.wdc.domain.po.PayOrder;
import com.wdc.domain.req.ShopCartReq;
import com.wdc.domain.res.PayOrderRes;
import com.wdc.domain.vo.ProductVO;
import com.wdc.service.IOrderService;
import com.wdc.service.rpc.ProductRPC;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 订单服务
 */

@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Resource
    private IOrderDao orderDao;

    @Resource
    private ProductRPC productRPC;


    @Override
    public PayOrderRes createOrder(ShopCartReq shopCartReq) {
        //1.查询未支付的订单
        PayOrder payOrderReq = new PayOrder();
        payOrderReq.setUserId(shopCartReq.getUserId());
        payOrderReq.setProductId(shopCartReq.getProductId());
        PayOrder unPayOrder = orderDao.queryUnPayOrder(payOrderReq);

        if (null != unPayOrder && Constants.OrderStatusEnum.PAY_WAIT.getCode().equals(unPayOrder.getStatus())) {
            log.info("创建订单-存在， 已存在未支付订单 userId: {} productId: {} orderId: {}", shopCartReq.getUserId(), shopCartReq.getProductId());
            return PayOrderRes.builder()
                    .orderId(unPayOrder.getOrderId())
                    .payUrl(unPayOrder.getPayUrl())
                    .build();
        }else if (null != unPayOrder && Constants.OrderStatusEnum.CREATE.getCode().equals(unPayOrder.getStatus())){
            // todo wdc
        }

        //2. 查询商品 & 创建订单
        ProductVO productVO = productRPC.queryProductByProductId(shopCartReq.getProductId());
        String orderId = RandomStringUtils.randomNumeric(16);
        orderDao.insert(PayOrder.builder()
                .userId(shopCartReq.getUserId())
                .productId(shopCartReq.getProductId())
                .productName(productVO.getProductName())
                .orderId(orderId)
                .totalAmount(productVO.getPrice())
                .orderTime(new Date())
                .status(Constants.OrderStatusEnum.CREATE.getCode())
                .build());

        // 3. 创建支付单 todo

        return PayOrderRes.builder()
                .orderId(orderId)
                .payUrl("暂无")
                .build();
    }
}
